<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Send;
use think\Config;
use think\Request;
use think\Db;


/**
 * 示例接口2
 */
class Mall extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
	 
	public function _initialize()
    {
        parent::_initialize();
		$this->config = array(
			'app_id' =>'wx5dd295e6ff41914c', //小程序appid
			'mchid'  => 1618373364, //商户号
			'apikey' =>'huantengqishihuantengqishihuante'  //秘钥
		);
    }
	//商城商品分类
    public function index(){
		$cate=db('cate')->select();
		$cate_id=input("cate_id")?input("cate_id"):0;
		$map['status']=1;
		if($cate_id!=0){
			$map['cate_id']=$cate_id;
		}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$goods=db('goods')->where($map)->limit($start,$pagesize)->select();
		 $data['sta']=1;
		 $data['cate']=$cate;
		 $data['goods']=$goods;
		 return json($data);
	}
	//商品详情
	public function detail(){
		$id=input("id")?input("id"):0;
		if($id==0){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$detail=db('goods')->find($id);
		if(empty($detail)){
			$data['sta']=0;
			$data['msg']="商品不存在";
			return json($data);
		}
		if($detail['status']!=1){
			$data['sta']=0;
			$data['msg']="商品状态有误";
			return json($data);
		}
		 $data['sta']=1;
		 $data['detail']=$detail;
		 return json($data);
	}
	
	//添加地址
	public function add_address(){
		$uid=input('uid');
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$name=input('name');
		$mobile=input('mobile');
		if(empty($name)||empty($mobile)){
			$data['sta']=0;
			$data['msg']="请输入姓名和电话";
			return json($data);
		}
		$addr=input('addr');
		$address=input('address');
		if(empty($addr)||empty($address)){
			$data['sta']=0;
			$data['msg']="请输入地址";
			return json($data);
		}
		$addrs['user_id']=$uid;
		$addrs['name']=$name;
		$addrs['mobile']=$mobile;
		$addrs['addr']=$addr;
		$addrs['address']=$address;
		$addrs['createtime']=time();
		$od=db('address')->where('user_id',$uid)->where('status',1)->where('is_default',1)->find();
		if(empty($od)){
			$addrs['is_default']=1;
		}
		Db::startTrans();
		try{
			db('address')->insertGetId($addrs);
			Db::commit();
			$data['sta']=1;
			$data['msg']="操作成功";
			return json($data);
		}catch(\Exception $e){
			Db::rollback();
			$data['sta']=0;
			$data['msg']=$e->getMessage();
			return json($data);
		}
	}
	//地址列表
	public function address_list(){
		$uid=input('uid');
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$list=db('address')->where("user_id",$uid)->where("status",1)->order("is_default","desc")->order("createtime","desc")->select();
		if(empty($list)){
			$data['sta']=0;
			$data['msg']="";
			return json($data);
		}else{
			$data['sta']=1;
			$data['msg']=$list;
			return json($data);
		}
	}
	//删除地址
	public function address_del(){
		$uid=input('uid');
		$address_id=input('address_id');
		if(empty($uid)||empty($address_id)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$address=db('address')->find($address_id);
		if(empty($address)){
			$data['sta']=0;
			$data['msg']="地址不存在";
			return json($data);
		}
		if($address['user_id']!=$uid){
			$data['sta']=0;
			$data['msg']="无操作权限";
			return json($data);
		}
		if($address['status']!=1){
			$data['sta']=0;
			$data['msg']="状态有误";
			return json($data);
		}
		$address['status']=2;
		Db::startTrans();
		try{
			db('address')->update($address);
			Db::commit();
			$data['sta']=1;
			$data['msg']="操作成功";
			return json($data);
		}catch(\Exception $e){
			Db::rollback();
			$data['sta']=0;
			$data['msg']=$e->getMessage();
			return json($data);
		}
	}
	//设为默认地址
	public function address_default(){
		$uid=input('uid');
		$address_id=input('address_id');
		if(empty($uid)||empty($address_id)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$address=db('address')->find($address_id);
		if(empty($address)){
			$data['sta']=0;
			$data['msg']="地址不存在";
			return json($data);
		}
		if($address['user_id']!=$uid){
			$data['sta']=0;
			$data['msg']="无操作权限";
			return json($data);
		}
		if($address['status']!=1){
			$data['sta']=0;
			$data['msg']="状态有误";
			return json($data);
		}
		if($address['is_default']==1){
			$data['sta']=0;
			$data['msg']="已经是默认地址了";
			return json($data);
		}
		$address['is_default']=1;
		Db::startTrans();
		try{
			
			$odf=db('address')->where('user_id',$uid)->where('is_default',1)->select();
			if(!empty($odf)){
				foreach($odf as $k=>$v){
					$odf[$k]["is_default"]=0;
					db('address')->update($odf[$k]);
				}
			}
			db('address')->update($address);
			Db::commit();
			$data['sta']=1;
			$data['msg']="操作成功";
			return json($data);
		}catch(\Exception $e){
			Db::rollback();
			$data['sta']=0;
			$data['msg']=$e->getMessage();
			return json($data);
		}
	}
	//地址和优惠券
	public function get_addr(){
		$uid=input('uid');
		$type=input('type')?input('type'):"goods";
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		if($type=="goods"){
			$address_id=input('address_id')?input('address_id'):0;
			
			if($address_id==0){
				$addr=db('address')->where('user_id',$uid)->where('is_default',1)->where('status',1)->find();
			}else{
				$addr=db('address')->where('id',$address_id)->where('user_id',$uid)->where('status',1)->find();
			}
			if(empty($addr)){
				$addr=db('address')->where('user_id',$uid)->where('status',1)->find();
			}
			if(empty($addr)){
				$data['sta']=0;
				$data['msg']="地址为空";
				return json($data);
			}
			$user=db('user')->where('id',$uid)->field('id,is_new')->find();
			if($user['is_new']==1){
				$card=array('man'=>10,'jian'=>10);
				$data['card']=$card;
			}
			
			$data['sta']=1;
			$data['addr']=$addr;
			return json($data);
		}else{
			$ticket_id=input('ticket_id')?input('ticket_id'):0;
			 
			$num=(int)input('num')?(int)input('num'):1;
			if($ticket_id==0){
				$data['sta']=0;
				$data['msg']="参数错误";
				return json($data);
			}
			$ticket=db('ticket')->find($ticket_id);
			if(empty($ticket)){
				$data['sta']=0;
				$data['msg']="信息有误";
				return json($data);
			}
			$zj=$ticket['price']*$num;
			$card=db('card')->where('shop_id',$ticket['shop_id'])->where('man','elt',$zj)->order('jian',"desc")->find();
			$shop=db('shop')->find($ticket['shop_id']);
			$data['sta']=1;
			$data['ticket']=$ticket;
			$data['card']=$card;
			$data['shop']=$shop;
			return json($data);
		}
	}
	//订单页面
	public function before_order(){
		$uid=input('uid');
		$user=db('user')->find($uid);
		if(empty($user)){
			$data['sta']=0;
			$data['msg']="用户信息有误";
			return json($data);
		}
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$type=input('type')?input('type'):"goods";
		$goods=$this->request->post('goods/a');
		if(empty($goods)){
			$data['sta']=0;
			$data['msg']="商品信息有误";
			return json($data);
		}
		$name="";
		$mobile="";
		$address="";
		$money=0;
		$shop_id=0;
		$card_id=0;
		$ids="";
		if($type=="goods"){
			 $name=input('name');
			 $mobile=input('mobile');
			 $address=input('address');
			 if(empty($name)||empty($mobile)||empty($address)){
				$data['sta']=0;
				$data['msg']="请输入收货信息";
				return json($data);
			 }
			 foreach($goods as $k=>$v){
				 $good=db('goods')->where('status',1)->where('id',$v["id"])->find();
				 if(empty($good)){
					$data['sta']=0;
					$data['msg']="商品信息有误";
					return json($data);
				 }
				 $money+=$good['price']*$v['num'];
				 $ids=$ids.$v['id'].",";
			 }
		 
			if($user['is_new']==1){
				$money=$money-10>0.01?($money-10):0.01;	
				$card_id=1;			
			}
		}else{
			$card_id=(int)input('card_id')?(int)input('card_id'):0;
			$card=array();
			if($card_id!=0){
				$card=db("card")->find($card_id);
			}
			foreach($goods as $k=>$v){
				$good=db('ticket')->where('status',1)->where('id',$v["id"])->find();
				if(empty($good)){
					$data['sta']=0;
					$data['msg']="商品信息有误";
					return json($data);
				}
				if($v['num']>$good['dnum']){
					
				}
				$money+=$good['price']*$v['num'];
				$ids=$ids.$v['id'].",";
			}
			$shop_id=$good['shop_id'];
			if(!empty($card)){
				if($money<$card['man']){
					$data['sta']=0;
					$data['msg']="不符合优惠券使用条件";
					return json($data);
				}
				$money=$money-$card['jian'];
				
			}
		}
		$money=round($money,2);
	
		$order['orderon']=date("YmdHis").mt_rand(10000000,99999999);
		$order['type']=$type;
		$order['user_id']=$uid;
		$order['shop_id']=$shop_id;
		$order['card_id']=$card_id;
		$order['price']=$money;
		$order['ids']=$ids;
		$order['createtime']=time();
		$order['mobile']=$mobile;
		$order['address']=$address;
		$order['name']=$name;
		$order['deltime']=time()+900;
		$order['json']=json_encode($goods);
		if($shop_id!=0){
			$shop=db('shop')->find($shop_id);
			if(!empty($shop)){
				$order["js_money"]=$order['price']*(100-$shop['dian'])/100;
			}
		}
		
		
		Db::startTrans();
		try{
			$order_id=db('order')->insertGetId($order);
			Db::commit();
			$data['sta']=1;
			$data['wxParams'] = $this->unifiedorder($order['orderon'], $user['openid'], $order['price'],"商品购买");
			$data['msg']="操作成功";
			return json($data);
		}catch(\Exception $e){
			Db::rollback();
			$data['sta']=0;
			$data['msg']=$e->getMessage();
			return json($data);
		}
	}
	
	//提交订单
	public function unifiedorder($order_sn, $openid, $total_fee,$title)
	{
		// 当前时间
		$time = time();
		// 生成随机字符串
		$nonceStr = md5($time . $openid);
		// API参数
		$params = [
			'appid' => $this->config['app_id'],
			'attach' =>$title,
			'body' => $order_sn,
			'mch_id' => $this->config['mchid'],
			'nonce_str' => $nonceStr,
			'notify_url' =>"https://horse.molijuhe.com/api/mall/notify/order_sn/".$order_sn,  // 异步通知地址
			'openid' => $openid,
			'out_trade_no' => $order_sn,
			'spbill_create_ip' => \request()->ip(),
			'total_fee' => $total_fee * 100, // 价格:单位分
			'trade_type' => 'JSAPI',
		];
		 
		// 生成签名
		$params['sign'] = $this->makeSign($params); 
		// 请求API
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$result = $this->postXmlCurl($this->toXml($params), $url);
		$prepay = $this->fromXml($result);
 
		// 请求失败
		if ($prepay['return_code'] === 'FAIL') {
			return [
				'sta'=>0,
				'msg'=>$prepay['return_msg']
			];
		}
		if ($prepay['result_code'] === 'FAIL') {
			return [
				'sta'=>0,
				'msg'=>$prepay['return_msg']
			];
		}
		// 生成 nonce_str 供前端使用
		$paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
		return [
			'sta'=>1,
			'prepay_id' => $prepay['prepay_id'],
			'nonceStr' => $nonceStr,
			'timeStamp' => (string)$time,
			'paySign' => $paySign,
			'order_sn' => $order_sn
		];
	}
	 
	/**
	 * 以post方式提交xml到对应的接口url
	 * @param $xml
	 * @param $url
	 * @param int $second
	 * @return mixed
	 */
	public function postXmlCurl($xml, $url, $second = 30){
		$ch = curl_init();
		// 设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//严格校验
		// 设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		// 要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		// post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		// 运行curl
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
	 
	/**
	 * 输出xml字符
	 * @param $values
	 * @return bool|string
	 */
	public function toXml($values)
	{
		if (!is_array($values)
			|| count($values) <= 0
		) {
			return false;
		}
	 
		$xml = "<xml>";
		foreach ($values as $key => $val) {
			if (is_numeric($val)) {
				$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
			} else {
				$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
			}
		}
		$xml .= "</xml>";
		return $xml;
	}
	 
	/**
	 * 将xml转为array
	 * @param $xml
	 * @return mixed
	 */
	public function fromXml($xml)
	{
		// 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	}
	 
	/**
	 * 生成签名
	 * @param $values
	 * @return string 本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	public function makeSign($values){
		//签名步骤一：按字典序排序参数
		ksort($values);
		$string = $this->toUrlParams($values);
		//签名步骤二：在string后加入KEY
		$string = $string . '&key=' . $this->config['apikey'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
 
	/**
	 * 生成paySign
	 * @param $nonceStr
	 * @param $prepay_id
	 * @param $timeStamp
	 * @return string
	 */
	public function makePaySign($nonceStr, $prepay_id, $timeStamp)
	{
		$data = [
			'appId' => $this->config['app_id'],
			'nonceStr' => $nonceStr,
			'package' => 'prepay_id=' . $prepay_id,
			'signType' => 'MD5',
			'timeStamp' => $timeStamp,
		];
	 
		//签名步骤一：按字典序排序参数
		ksort($data);
	 
		$string = $this->toUrlParams($data);
	 
		//签名步骤二：在string后加入KEY
		$string = $string . '&key=' . $this->config['apikey'];
	 
		//签名步骤三：MD5加密
		$string = md5($string);
	 
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
	 
		return $result;
	}
 
	/**
	 * 格式化参数格式化成url参数
	 * @param $values
	 * @return string
	 */
	public function toUrlParams($values)
	{
		$buff = '';
		foreach ($values as $k => $v) {
			if ($k != 'sign' && $v != '' && !is_array($v)) {
				$buff .= $k . '=' . $v . '&';
			}
		}
		return trim($buff, '&');
	}
 
	//随机字符串
	public function createNonceStr($length = 16) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
	//支付回调
	public function notify($order_sn=''){
		 
		$order=db('order')->where('orderon',$order_sn)->find();
		if(empty($order)){
			$this->error('订单不存在');
		}
		 
		if($order['status']!=0){
			$rearr['return_code']="SUCCESS";
			$rearr['return_msg']="OK";
			return $this->toXml($rearr);
		}
		$duizhang=$this->duizhang($order_sn);
 
		 if($duizhang){
			 Db::startTrans();
			try { 
				//更新订单状态
				$order['status']=1;
				$order['paytime']=strtotime($duizhang['time_end']);
				db('order')->update($order);
					//商品订单更新销量
				if($order['type']=="goods"){
					$json=json_decode($order['json'],true);
					foreach($json as $k=>$v){
						$goods=db('goods')->find($v['id']);
						$goods['sold_num']=$goods['sold_num']+$v['num'];
						db('goods')->update($goods);
					}
				}
				//新人优惠券只能用一次
				if($order['card_id']==1){
					$user=db('user')->find($order["user_id"]);
					$user['is_new']=0;
					db('user')->update($user);
				}
				
				Db::commit();
				$rearr['return_code']="SUCCESS";
				$rearr['return_msg']="OK";
				return $this->toXml($rearr);
			}catch (\Exception $e){
				Db::rollback();
				$this->error($e->getMessage());
			}	
		 }
		
	}
	//订单验证
	public  function duizhang($orderid){
		 $unified = [
			'appid' => $this->config['app_id'],
            'mch_id' => $this->config['mchid'],
			'out_trade_no' => $orderid, //商户订单号
			'nonce_str' =>$this->createNonceStr(),	 
		];
        $order=db('order')->where('orderon',$orderid)->find();
		 
		$unified['sign'] = $this->makeSign($unified);
		$url = 'https://api2.mch.weixin.qq.com/pay/orderquery';
		$responseXml = $this->postXmlCurl($this->toXml($unified), $url);
		$unifiedOrder = $this->fromXml($responseXml);
		 
		if (empty($unifiedOrder)) {
			return false;
        }
        if ($unifiedOrder['return_code'] != 'SUCCESS'){
			return false;
        }
        if ($unifiedOrder['result_code'] != 'SUCCESS'){
			return false;
        }
		if($unifiedOrder['total_fee']!=$order['price']*100){
				return false;
		}
		if($unifiedOrder['trade_state']=='SUCCESS'&&$unifiedOrder['result_code']=='SUCCESS'){
			 return $unifiedOrder;
		}else{
			 return false;
		}
	}
	//我的订单
	public function myorder(){
		$uid=input('uid');
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$status=input('status')?input('status'):0;
		$type=input('type')?input('type'):"goods";
		$map['type']=$type;
		$map['user_id']=$uid;
		if($type=="goods"&&$status==0){
			$map['status']=array('in',array(1,2,8));
		}else{
			$map['status']=$status;
		}
		
		$list=db('order')->where($map)->order('createtime',"desc")->limit($start,$pagesize)->select();
		if($type=="goods"){
			foreach($list as $k=>$v){
				$list[$k]['ids']=explode(',',trim($v["ids"],','));
				$list[$k]['json']=json_decode($v['json'],true);
				$list[$k]['count']=0;
				foreach($list[$k]['json'] as $k1=>$v1){
					$list[$k]['count']=$list[$k]['count']+$v1['num'];
				}
				$list[$k]['goods']=db('goods')->find($list[$k]['json'][0]["id"]);
				$list[$k]['goods']['count']=$list[$k]['json'][0]["num"];
			}	
		}else{
			foreach($list as $k=>$v){
				$list[$k]['ids']=explode(',',trim($v["ids"],','));
				$list[$k]['json']=json_decode($v['json'],true);
				$list[$k]['count']=0;
				foreach($list[$k]['json'] as $k1=>$v1){
					$list[$k]['count']=$list[$k]['count']+$v1['num'];
				}
				$list[$k]['goods']=db('ticket')->find($list[$k]['json'][0]["id"]);
			}
		}
		$data['sta']=1;
		$data['msg']=$list;
		return json($data);
	}
	//订单详情
	public function order_detail(){
		$uid=input('uid');
		$order_id=input('order_id');
		if(empty($uid)||empty($order_id)){
			$data['sta']=0;
			$data['msg']="参数有误";
			return json($data);
		}
		$order=db('order')->find($order_id);
		if(empty($order)){
			$data['sta']=0;
			$data['msg']="订单不存在";
			return json($data);
		}
		if($order['user_id']!=$uid){
			$data['sta']=0;
			$data['msg']="无权限";
			return json($data);
		}
		$order['ids']=explode(',',trim($order["ids"],','));
		$order['goods']=db($order['type'])->where('id','in',$order['ids'])->select();
		if($order['type']=="ticket"){
			$order['shop']=db('shop')->find($order['shop_id']);
		}
		$data['sta']=1;
		$data['msg']=$order;
		return json($data);
	}
	//获取票务
	public function get_ticket(){
		$uid=input('uid');
		$order_id=input('order_id');
		if(empty($uid)||empty($order_id)){
			$data['sta']=0;
			$data['msg']="参数有误";
			return json($data);
		}
		$order=db('order')->find($order_id);
		if(empty($order)){
			$data['sta']=0;
			$data['msg']="订单不存在";
			return json($data);
		}
		if($order['type']!="ticket"){
			$data['sta']=0;
			$data['msg']="信息有误";
			return json($data);
		}
		if($order['status']!=1){
			$data['sta']=0;
			$data['msg']="订单状态有误";
			return json($data);
		}
		$admin=db('ShopAdmin')->where('shop_id',$order['shop_id'])->where('is_admin','in',array(1,3))->find();
		if(empty($admin)){
			$data['sta']=0;
			$data['msg']="无操作权限";
			return json($data);
		}
		$order['ids']=explode(',',trim($order["ids"],','));
		$order['goods']=db('ticket')->find($order['ids'][0]);
		$order['shop']=db('shop')->find($order['goods']['shop_id']);
		$order['json']=json_decode($order['json'],true);
		$order['user']=db('user')->field('nickname,mobile')->find($order['user_id']);
			$data['sta']=1;
			$data['msg']=$order;
			return json($data);
	}
	//门票审核
	public function ticket_auto(){
		$uid=input('uid');
		$order_id=input('order_id');
		$remark=input('remark');
		if(empty($uid)||empty($order_id)){
			$data['sta']=0;
			$data['msg']="参数有误";
			return json($data);
		}
		$order=db('order')->find($order_id);
		if(empty($order)){
			$data['sta']=0;
			$data['msg']="订单不存在";
			return json($data);
		}
		if($order['status']!=1){
			$data['sta']=0;
			$data['msg']="订单状态有误";
			return json($data);
		}
		$admin=db('ShopAdmin')->where('shop_id',$order['shop_id'])->where('is_admin','in',array(1,3))->find();
		if(empty($admin)){
			$data['sta']=0;
			$data['msg']="无操作权限";
			return json($data);
		}
		Db::startTrans();
		try { 
			$order['status']=8;
			db('order')->update($order);
				$auto['user_id']=$order['user_id'];
				$auto['admin_id']=$admin['id'];
				$auto['shop_id']=$order['shop_id'];
				$auto['ticket_id']=$order['ids'];
				$auto['order_id']=$order_id;
				$auto['remark']=$remark;
				$auto['createtime']=time();
				db('TicketAuto')->insertGetId($auto);
			Db::commit();
			$data['sta']=1;
			$data['msg']="核销成功";
			return json($data);
		}catch (\Exception $e){
			Db::rollback();
			 $data['sta']=0;
			$data['msg']=$e->getMessage();
			return json($data);
		}	 
	}
	//核销历史
	public function ticket_history(){
		$uid=input("uid");
		$shop_id=input("shop_id");
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$admin=db('ShopAdmin')->where('user_id',$uid)->where('shop_id',$shop_id)->where('is_admin','in',array(1,3))->find();
		if(empty($admin)){
			$data['sta']=0;
			$data['msg']="无操作权限";
			return json($data);
		}
		$list=db('TicketAuto')
			->field('shop.name as shop_name,horse_ticket_auto.*,ticket.name as ticket_name,order.price,user.nickname as user_name,user.mobile')
			->join('order',"order.id=horse_ticket_auto.order_id")
			->join('user',"user.id=horse_ticket_auto.user_id")
			->join('shop',"shop.id=horse_ticket_auto.shop_id")
			->join('ticket',"ticket.id=horse_ticket_auto.ticket_id")
			->where('horse_ticket_auto.shop_id',$shop_id)
			->limit($start,$pagesize)
			->order('horse_ticket_auto.createtime',"desc")
			->select();
		if(empty($list)){
			$data['sta']=0;
			$data['msg']="";
			return json($data);
		}else{
			$data['sta']=1;
			$data['msg']=$list;
			return json($data);
		}
	}
	//店铺列表
	public function shop(){
		$order = ['distance' => 'asc']; 
		$where['switch']=1;
		$where['status']=1;
		$lat=input("lat")?input("lat"):'37.736933';
		$lng=input("lng")?input("lng"):'112.562646';
		
		$keyword=input('keyword');
		if(!empty($keyword)){
			$where["name|addr"]=array("like","%".$keyword."%");
		}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$list=db('shop')
			->field("id,user_id,name,uname,lat,lng,mobile,times,addr,address,status,images,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
			->where($where)
			->order($order)
			->limit($start,$pagesize)
			->select();
			if(!empty($list)){
				foreach($list as $k=>$v){
					$list[$k]["distance"]=round($v['distance'] / 1000, 2) < 1 ? ceil($v['distance']) . 'm' : round($v['distance']/ 1000, 2) . 'km'; 
				}
				$data['sta']=1;
				$data['msg']=$list;
				return json($data);
			}else{
				$data['sta']=0;
				$data['msg']="";
				return json($data);
			}
	}
	public function shop_detail(){
		$shop_id=input("shop_id");
		$uid=input("uid")?input("uid"):0;
		if(empty($shop_id)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$shop=db('shop')->find($shop_id);
		if(empty($shop)){
			$data['sta']=0;
			$data['msg']="店铺信息有误";
			return json($data);
		}
		if($shop['switch']==0){
			$data['sta']=0;
			$data['msg']="店铺未审核";
			return json($data);
		}
		$shop['card']=db("card")->where('shop_id',$shop_id)->where('status',1)->order("createtime","desc")->select();
		if($uid!=0){
			$vip=db("ShopVip")->where("user_id",$uid)->where('shop_id',$shop_id)->where("status",1)->find();
			$fav=db('ShopFav')->where("user_id",$uid)->where('shop_id',$shop_id)->find();
		}
		if(empty($vip)){
			$shop['tickets']=db("ticket")->where('shop_id',$shop_id)->where('status',1)->limit(0,3)->where('type',1)->order("createtime","desc")->select();
		}else{
			$shop['tickets']=db("ticket")->where('shop_id',$shop_id)->where('status',1)->limit(0,3)->order("createtime","desc")->select();
		}
			$shop['class']=db("class")->where('shop_id',$shop_id)->where('status',1)->limit(0,4)->order("createtime","desc")->select();
			if(!empty($fav)){
				$shop['fav']=$fav;
			}
			$data['sta']=1;
			$data['msg']=$shop;
			return json($data);
	}
	public function ticket_list(){
		$shop_id=input('shop_id');
		if(empty($shop_id)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$uid=input("uid")?input("uid"):0;
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$keyword=input('keyword');
		$type=input("type")?input("type"):"ticket";
		if(!empty($keyword)){
			$where["name"]=array("like","%".$keyword."%");
		}
		if($type=="ticket"){
			if($uid!=0){
				$vip=db("ShopVip")->where("user_id",$uid)->where('shop_id',$shop_id)->where("status",1)->find();
			}
			if(empty($vip)){
				$tickets=db("ticket")->where('status',1)->where('shop_id',$shop_id)->limit($start,$pagesize)->where('type',1)->order("createtime","desc")->select();
			}else{
				$tickets=db("ticket")->where('status',1)->where('shop_id',$shop_id)->limit($start,$pagesize)->order("createtime","desc")->select();
			}	
		}else{
			$tickets=db("class")->where('status',1)->where('shop_id',$shop_id)->limit($start,$pagesize)->order("createtime","desc")->select();
		}
		
		if(empty($tickets)){
			$data['sta']=0;
			$data['msg']="";
			return json($data);
		}else{
			$data['sta']=1;
			$data['msg']=$tickets;
			return json($data);	
		}	
	}
	public function search(){
		$where=array();
		$keyword=input('keyword');
		if(!empty($keyword)){
			$where["name"]=array("like","%".$keyword."%");
		}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$where['status']=1;
		$list=db('goods')->where($where)->limit($start,$pagesize)->order("createtime","desc")->select();
		if(empty($list)){
			$data['sta']=0;
			$data['msg']="";
			return json($data);	
		}else{
			$data['sta']=1;
			$data['msg']=$list;
			return json($data);	
		}
	}
	public function mall(){
		$order = ['distance' => 'asc']; 
		$where['switch']=1;
		$where['status']=1;
		$lat=input("lat")?input("lat"):'37.736933';
		$lng=input("lng")?input("lng"):'112.562646';

		$list=db('shop')
			->field("id,user_id,name,uname,lat,lng,mobile,times,addr,address,status,images,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
			->where($where)
			->order($order)
			->limit(0,3)
			->select();
			if(!empty($list)){
				foreach($list as $k=>$v){
					$list[$k]["distance"]=round($v['distance'] / 1000, 2) < 1 ? ceil($v['distance']) . 'm' : round($v['distance']/ 1000, 2) . 'km'; 
				}
			}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$where1['status']=1;
		$goods=db('goods')->where($where1)->limit($start,$pagesize)->order("createtime","desc")->select();
		$data['sta']=1;
		$data['shop']=$list;
		$data['goods']=$goods;
		return json($data);
	}
	public function shop_fav(){
		$uid=input('uid');
		$shop_id=input('shop_id');
		if(empty($uid)||empty($shop_id)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json_encode($data);
		}
		$fav['shop_id']=$shop_id;
		$fav['user_id']=$uid;
		$favs=db('ShopFav')->where($fav)->find();
		if(empty($favs)){
			$fav['createtime']=time();
			Db::startTrans();
			try { 
				db('ShopFav')->insertGetId($fav);
				Db::commit();
				$data['sta']=1;
				$data['msg']="收藏成功";
				return json($data);				
			}catch (\Exception $e){
				Db::rollback(); 
				$data['sta']=0;
				$data['msg']=$e->getMessage();
				return json($data);
			}	
		}else{
			Db::startTrans();
			try { 
				db('ShopFav')->delete($favs['id']);
				Db::commit();
				$data['sta']=2;
				$data['msg']="取消成功";
				return json($data);		
			}catch (\Exception $e){
				Db::rollback();
				$data['sta']=0;
				$data['msg']=$e->getMessage();
				return json($data);  
			}	
		}
	}
	public function my_fav(){
		$uid=input("uid");
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$page=input('page')?input('page'):1;
		$pagesize=input('pagesize')?input('pagesize'):10;
		$start=($page-1)*$pagesize;
		$list=db('ShopFav')->join("shop","shop.id=horse_shop_fav.shop_id")->limit($start,$pagesize)->where('horse_shop_fav.user_id',$uid)->select();
		if(empty($list)){
			$data['sta']=0;
			$data['msg']="";
			return json($data);
		}else{
			$data['sta']=1;
			$data['msg']=$list;
			return json($data);
		}
	}
	public function fav_count(){
		$uid=input("uid");
		if(empty($uid)){
			$data['sta']=0;
			$data['msg']="参数错误";
			return json($data);
		}
		$count=db('ShopFav')->where('user_id',$uid)->count();
			$data['sta']=0;
			$data['msg']=$count;
			return json($data);
	}
	 
}
